﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using GadgetBase;

namespace Sidebar
{
    public static class ModuleManager
    {

        public static Assembly[] SearchAssemblys(string localDirectory)
        {
            string fullPath = GlobalMethods.GetFullPath(localDirectory);

            string[] files = Directory.GetFiles(fullPath, @"*.dll", SearchOption.AllDirectories);

            List<Assembly> assemblys = new List<Assembly>();
            foreach (string path in files)
            {
                assemblys.Add(Assembly.LoadFile(path));
            }

            return assemblys.ToArray();
        }


        public static GadgetWindow GetGadget(Assembly assembly)
        {
            foreach (Type type in assembly.GetTypes())
            {
                if (type.BaseType == typeof(GadgetWindow))
                {
                    object gadget = assembly.CreateInstance(type.FullName);
                    return (GadgetWindow)gadget;
                }
            }
            return null;
        }


        public static GadgetWindow[] SearchGadgets(string localDirectory)
        {
            List<GadgetWindow> list = new List<GadgetWindow>();
            
            foreach (Assembly assembly in SearchAssemblys(localDirectory))
            {
                try
                {
                    GadgetWindow gadget = GetGadget(assembly);
                    list.Add(gadget);
                }
                catch (System.Exception e)
                {
                    System.Diagnostics.Debug.Assert(false, string.Format("Error of loading of {0}\n\n{1}", Path.GetFileName(Path.GetDirectoryName(assembly.Location)) + Path.DirectorySeparatorChar + Path.GetFileName(assembly.Location), e));
                }
            }

            return list.ToArray();
        }


    }
}
